/* eslint-disable no-param-reassign */
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { TreeSelect } from 'antd';
import { get as getPath } from 'object-path';
import request from '@/utils/request';
import Locale from '@/utils/locale';

const { locale } = new Locale('component.companyDepart');

const getTreeData = (data = [], fieldsName = { value: 'id', title: 'companyName' }) => {
    if (fieldsName.TypeRemak) {
        return data.map(item => ({
            ...item,
            value: `${item[fieldsName.value]}`,
            title: item[fieldsName.title],
            companyTypeRemak: `${item[fieldsName.TypeRemak]}`,
            key: `${item[fieldsName.value]}`,
            children: item.children ? getTreeData(item.children, fieldsName) : item.children
        }));
    }
    return data.map(item => ({
        ...item,
        value: item[fieldsName.value],
        title: item[fieldsName.title],
        key: item[fieldsName.value],
        children: item.children ? getTreeData(item.children, fieldsName) : item.children
    }));
};

const CompanyType = React.forwardRef(
    (
        {
            onChange,
            value,
            companyProps,
            departmentProps,
            customDepartmentRequest,
            // onlyLevelOne,
            permissionCode
            // onReady
            // ...rest
        },
        ref
    ) => {
        const { companyId, departmentId } = value;
        const [companyTree, setCompanyTree] = useState([]);
        const [departmentTree, setDepartmentTree] = useState([]);

        const fetchCompanyTree = async () => {
            const params = {
                companyId,
                permissionUrl: permissionCode
            };

            const result = await request('/api/org/v1/functional/list', {
                params
            });

            if (result && result.code === 10000) {
                setCompanyTree(result.data || []);
            }
        };
        // TODO 移除这种拼接的写法
        const handleCompanyChange = (e, option, extra) => {
            onChange({
                companyId: e,
                departmentId: undefined,
                companyTypeRemak: getPath(extra, 'triggerNode.props.companyTypeRemak', null)
            });
        };

        const handleDepartmentChange = newValue => {
            onChange({
                companyId,
                departmentId: newValue
            });
        };

        const fetchDepartmentTree = async () => {
            if (!companyId) return;
            const params = {
                companyId
            };
            // 都不需要传部门id了，全部走权限
            // if (!onlyLevelOne) {
            //     params.departmentId = departmentId;
            // }
            params.permissionUrl = permissionCode;
            const result = await request(customDepartmentRequest.url, {
                params
            });
            if (result && result.code === 10000) {
                // 如果当前用户部门id没有匹配上时才选中列表第一个
                // if (
                //     result.data.length > 0 &&
                //     !result.data.find(item => item.id === user.departmentId)
                // ) {
                //     console.log()
                //     handleDepartmentChange(null);
                // }
                setDepartmentTree(result.data || []);
            }
        };

        useEffect(() => {
            fetchCompanyTree();
        }, []);
        useEffect(() => {
            if (companyId) {
                fetchDepartmentTree();
            } else {
                setDepartmentTree([]);
            }
        }, [companyId]);
        return (
            <div ref={ref}>
                <TreeSelect
                    showSearch
                    treeDefaultExpandAll
                    treeNodeFilterProp="title"
                    placeholder={locale('gs')}
                    style={{ width: 150 }}
                    allowClear={false}
                    value={companyId}
                    treeData={getTreeData(companyTree, {
                        value: 'id',
                        title: 'companyName',
                        TypeRemak: 'companyTypeRemak'
                    })}
                    onChange={handleCompanyChange}
                    {...companyProps}
                />
                <TreeSelect
                    showSearch
                    treeNodeFilterProp="title"
                    placeholder={locale('bm')}
                    style={{ width: 150, marginLeft: 10 }}
                    value={departmentId}
                    allowClear
                    treeData={getTreeData(departmentTree, {
                        value: 'id',
                        title: 'departmentName'
                    })}
                    onChange={handleDepartmentChange}
                    {...departmentProps}
                />
            </div>
        );
    }
);

CompanyType.propTypes = {
    onChange: PropTypes.func,
    /**
     * company的Select属性
     */
    companyProps: PropTypes.object,
    /**
     * department的Select属性
     */
    departmentProps: PropTypes.object,
    /**
     * 自定义部门请求
     */
    customDepartmentRequest: PropTypes.object,
    /**
     * 是否仅获取一级部门树
     */
    onlyLevelOne: PropTypes.bool,
    /**
     * 权限code
     */
    permissionCode: PropTypes.string.isRequired
};

CompanyType.defaultProps = {
    onChange: () => {},
    companyProps: {},
    departmentProps: {},
    customDepartmentRequest: {
        url: '/api/org/v1/functional/list'
    },
    onlyLevelOne: false
};

export default CompanyType;
